package oop.data;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import oop.db.dao.AnswerDAO;
import oop.db.dao.TextDAO;
import oop.db.dao.TopicDAO;
import oop.db.dao.UserDAO;

public class BaseQuestion implements Article {

	private long id;
	private long contentId;
	private int level;
	private long topicId;
	private Map<Long, Answer> answerMap = null;
	private List<Answer> answers = null;
	private long authorId;
	private Date createDate;

	public BaseQuestion(long id, long contentId, int level, long topicId,
			long authorId, Date createDate) {
		this.id = id;
		this.contentId = contentId;
		this.level = level;
		this.topicId = topicId;
		this.authorId = authorId;
		this.createDate = createDate;
	}

	public Map<Long, Answer> getAnswerById() throws SQLException {
		if (answerMap == null) {
			answerMap = new HashMap<Long, Answer>();
			for (Answer answer : getAnswers()) {
				answerMap.put(answer.getId(), answer);
			}
		}
		return answerMap;
	}

	public Collection<Answer> getAnswers() throws SQLException {
		if (answers == null) {
			answers = AnswerDAO.fetchByBaseQuestion(this);
		}
		return answers;
	}

	public long getId() {
		return id;
	}

	public Text getContent() throws SQLException {
		return TextDAO.fetch(contentId);
	}

	public void setContent(Text text) {
		this.contentId = text.getId();
	}
	
	public int getMark() {
		return 1;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public Topic getTopic() {
		return TopicDAO.fetchById(topicId);
	}

	public void setTopic(Topic topic) {
		this.topicId = topic.getId();
	}

	public User getAuthor() {
		return UserDAO.fetchById(authorId).get(0);
	}

	public Date getCreateDate() {
		return createDate;
	}
	
	public static String getLevelName(int level) {
		switch (level) {
		case 1:
			return "Rất khó";
		case 2:
			return "Khó";
		case 3:
			return "Trung bình";
		case 4:
			return "Dễ";
		case 5:
			return "Rất dễ";
		}
		return "<Không hợp lệ>";
	}

	@Override
	public Namespace getNamespace() {
		return Namespace.QUESTION;
	}

	@Override
	public String getName() {
		return String.valueOf(id);
	}
	
	@Override
	public String getQualifiedName() {
		return getNamespace().getName() + ":" + getName();
	}
	
}
